﻿Public Interface IContentModificationsSubriver
    ReadOnly Property subscribed As IContent
    Sub notificate()
End Interface

Public Class BaseContentModificationsSubriver
    Implements IContentModificationsSubriver

    Private _content As IContent
    Private _toDo As Action

    Public Sub New(content As IContent, toDo As Action)
        Me._content = content
        Me._toDo = toDo
    End Sub

    Public Sub notificate() Implements IContentModificationsSubriver.notificate
        _toDo.Invoke()
    End Sub

    Public ReadOnly Property subscribed As IContent Implements IContentModificationsSubriver.subscribed
        Get
            Return _content
        End Get
    End Property
End Class

<GlobalAvalibleObjectImplementation(singleton:=True)>
Public Class ContentModifications

    Private _subribed As ICollection(Of WeakReference) = New LinkedList(Of WeakReference)

    Private Shared _lock As New Object

    ''' <summary>
    ''' add a subriber, no need to unsbrive unless you want it
    ''' </summary>
    ''' <param name="item"></param>
    ''' <remarks>the reference is weak the subscriber if not reference will be destroyed</remarks>
    Public Sub subscrive(item As IContentModificationsSubriver)
        SyncLock _lock
            _subribed.Add(New WeakReference(item))
        End SyncLock
    End Sub

    Public Sub notificate(content As IContent)
        SyncLock _lock
            Dim new_list As ICollection(Of WeakReference) = New LinkedList(Of WeakReference)
            For Each wr As WeakReference In _subribed
                If Not wr.IsAlive Then Continue For
                Dim subscriber As IContentModificationsSubriver = wr.Target
                If subscriber Is Nothing Then Continue For

                new_list.Add(wr)

                Dim other_content As IContent = subscriber.subscribed
                If other_content Is Nothing Then Continue For
                If other_content.Equals(content) Then subscriber.notificate()
            Next
            _subribed = new_list
        End SyncLock
    End Sub

End Class
